//
//  XS_KCTitle.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/29.
//

import UIKit
import RxCocoa
import RxSwift

class XS_KCTitle: UIView {
    lazy var disposeBag = DisposeBag()
    lazy var modelPS = PublishSubject<(String, [String])>()
    override init(frame: CGRect) {
        super.init(frame: frame)
        upView()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func upView() {
        backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        let label = UILabel.xsLabel(size: .scale*20, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), lines: 0)
        label.tag = 101
        addSubview(label)
        label.snp.makeConstraints({
            $0.top.left.equalTo(.scale*16)
            $0.right.lessThanOrEqualTo(-.scale*16)
            $0.bottom.lessThanOrEqualTo(-.scale*12)
        })
        
        modelPS.subscribe(onNext: { title, tags in
            label.text = title
            self.removeSubviews([101])
            var last: UIView?
            for text in tags {
                let view = self.getTag(text)
                self.addSubview(view)
                view.snp.makeConstraints({
                    $0.height.equalTo(.scale*20)
                    $0.top.equalTo(label.snp.bottom).offset(.scale*8)
                    $0.bottom.lessThanOrEqualTo(-.scale*12)
                    if let last = last {
                        $0.left.equalTo(last.snp.right).offset(.scale*8)
                    } else {
                        $0.left.equalTo(.scale*16)
                    }
                })
                last = view
            }
        }).disposed(by: disposeBag)
    }
    
    func getTag(_ text: String) -> UIView {
        let view = UIView()
        view.layer.cornerRadius = .scale*10
        view.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        let label = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), text: text)
        view.addSubview(label)
        label.snp.makeConstraints({
            $0.center.equalToSuperview()
            $0.right.lessThanOrEqualTo(-.scale*6)
        })
        return view
    }
}
